package com.jm.utils.xml;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Vector;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.AttributesImpl;

import com.jm.utils.StringHelper;
import com.jm.web.data.BaseDataEntities;
import com.jm.web.form.Paging;

public class XmlUtils{
	SAXTransformerFactory fac = (SAXTransformerFactory) SAXTransformerFactory
			.newInstance();
	public static final String strSplit = "﹁";
	public static final String strEndChar = "#end#";
	private TransformerHandler handler = null;
	private OutputStream outStream = null;
	private String fileName;
	private AttributesImpl atts;
	
	public XmlUtils(String fileName) {
		this.fileName = fileName;
	}

	public void initWriter() {
		try {
			handler = fac.newTransformerHandler();
			Transformer transformer = handler.getTransformer();
			transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");// 设置输出采用的编码方式
			transformer.setOutputProperty(OutputKeys.INDENT, "no");// 是否自动添加额外的空白
			transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");// 是否忽略xml声明
			
			File file = new File(fileName);
			if(!file.getParentFile().exists())file.getParentFile().mkdirs();
			
			outStream = new FileOutputStream(file);
			Result resultxml = new StreamResult(outStream);
			handler.setResult(resultxml);
			atts = new AttributesImpl();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void write(ResultSet rs)
	throws Exception {
		initWriter();
		if(rs == null)return;
		//開始節點
		handler.startElement("", "", DataEntitiesHandler.VAR_ROOTNAME, atts);
		
		StringBuffer colName = new StringBuffer();
		ResultSetMetaData meta = rs.getMetaData();
		for (int i = 0; i < meta.getColumnCount(); i++) {
			colName.append(meta.getColumnName(i+1)) ;
			colName.append(XmlUtils.strSplit);
		}
		
		if(meta.getColumnCount() >0)colName.append(XmlUtils.strEndChar);
		
		//column節點
		handler.startElement("", "", DataEntitiesHandler.VAR_COLUMNNODENAME, atts);
		handler.characters(colName.toString().toCharArray(), 0, colName.length());
		handler.endElement("", "", DataEntitiesHandler.VAR_COLUMNNODENAME);
		
		while (rs.next()) {
			StringBuffer value = new StringBuffer();
			for (int i = 0; i < meta.getColumnCount(); i++) {
				value.append(StringHelper.getValue(rs.getString(i+1)));
				value.append(XmlUtils.strSplit);
			}
			if(meta.getColumnCount() >0)value.append(XmlUtils.strEndChar);
			//row 節點
			handler.startElement("", "", DataEntitiesHandler.VAR_ROWNODENAME, atts);
			handler.characters(value.toString().toCharArray(), 0, value.length());
			handler.endElement("", "",  DataEntitiesHandler.VAR_ROWNODENAME);
		}
		
		handler.endElement("", "", DataEntitiesHandler.VAR_ROOTNAME);
		handler.endDocument();
		outStream.close();
	}
	
	public void write(Vector vector)throws Exception {
		initWriter();
		if(vector == null) return;
		//開始節點
		handler.startElement("", "", VectorHandler.VAR_ROOTNAME, atts);
		
		if(vector != null && vector.size()>0){
			StringBuffer value = new StringBuffer();
			for(int i=0;i<vector.size();i++){
				value.append(StringHelper.getValue(vector.get(i)));
				value.append(XmlUtils.strSplit);
			}
			if(vector.size() > 0)value.append(XmlUtils.strEndChar);
			//data 節點
			handler.startElement("", "", VectorHandler.VAR_DATANODENAME, atts);
			handler.characters(value.toString().toCharArray(), 0, value.length());
			handler.endElement("", "", VectorHandler.VAR_DATANODENAME);
		}
		
		handler.endElement("", "", VectorHandler.VAR_ROOTNAME);
		handler.endDocument();
		outStream.close();
	}
	
	public BaseDataEntities getDataEntities(Paging paging){
		DataEntitiesHandler dataEntitiesHandler = new DataEntitiesHandler();
		dataEntitiesHandler.setPaging(paging);
		SAXParserFactory spf = SAXParserFactory.newInstance();  
		spf.setValidating(false);  
		SAXParser parser;
		try {
			parser = spf.newSAXParser();
			XMLReader myreader = parser.getXMLReader();  
			myreader.setContentHandler(dataEntitiesHandler);  
			InputSource source = new InputSource("file:///"+this.fileName);  
			myreader.parse(source);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return dataEntitiesHandler.getRows();
	}
	
	public Vector getVector(){
		VectorHandler vectorHandler = new VectorHandler();
		SAXParserFactory spf = SAXParserFactory.newInstance();  
		spf.setValidating(false);  
		SAXParser parser;
		try {
			parser = spf.newSAXParser();
			XMLReader myreader = parser.getXMLReader();  
			myreader.setContentHandler(vectorHandler);  
			InputSource source = new InputSource("file:///"+this.fileName);  
			myreader.parse(source);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return vectorHandler.getVector();
	}
	
}